/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
var reverseBetween = function (head, left, right) {
  if (left == 1) {
    return reverseN(head, right);
  }
  // 找到第 left 个节点的前驱
  let pre = head;
  for (let i = 1; i < left - 1; i++) {
    pre = pre.next;
  }
  // 从第 left 个节点开始反转
  pre.next = reverseN(pre.next, right - left + 1);
  return head;
};

function reverseN(head, n) {
  if (head == null || head.next == null) {
    return head;
  }
  let pre = null; cur = head; nxt = head.next;
  while (n--) {
    cur.next = pre;
    pre = cur;
    cur = nxt;
    if (nxt != null) {
      nxt = nxt.next;
    }
  }
  // 此时的 cur 是第 n + 1 个节点，head 是反转后的尾结点
  head.next = cur;
  // 此时的 pre 是反转后的头结点
  return pre;
}